package com.css.zfzx.sjcj.modules.hddcwyCrater.service.impl;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.analysis.vo.HddcAppZztCountVo;

import com.css.zfzx.sjcj.modules.hddcCrater.repository.HddcCraterNativeRepository;
import com.css.zfzx.sjcj.modules.hddcCrater.repository.HddcCraterRepository;
import com.css.zfzx.sjcj.modules.hddcCrater.repository.entity.HddcCraterEntity;
import com.css.zfzx.sjcj.modules.hddcwyCrater.repository.HddcWyCraterNativeRepository;
import com.css.zfzx.sjcj.modules.hddcwyCrater.repository.HddcWyCraterRepository;
import com.css.zfzx.sjcj.modules.hddcwyCrater.repository.entity.HddcWyCraterEntity;
import com.css.zfzx.sjcj.modules.hddcwyCrater.service.HddcWyCraterService;
import com.css.zfzx.sjcj.modules.hddcwyCrater.viewobjects.HddcWyCraterQueryParams;

import com.css.bpm.platform.api.local.PlatformAPI;

import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.modules.hddcwyCrater.viewobjects.HddcWyCraterVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author zhangcong
 * @date 2020-12-02
 */
@Service
public class HddcWyCraterServiceImpl implements HddcWyCraterService {

	@Autowired
    private HddcWyCraterRepository hddcWyCraterRepository;
    @Autowired
    private HddcWyCraterNativeRepository hddcWyCraterNativeRepository;
    @Autowired
    private HddcCraterRepository hddcCraterRepository;

    @Override
    public JSONObject queryHddcWyCraters(HddcWyCraterQueryParams queryParams,int curPage,int pageSize) {
        Page<HddcWyCraterEntity> hddcWyCraterPage = this.hddcWyCraterNativeRepository.queryHddcWyCraters(queryParams,curPage,pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcWyCraterPage);
        return jsonObject;
    }


    @Override
    public HddcWyCraterEntity getHddcWyCrater(String uuid) {
        HddcWyCraterEntity hddcWyCrater = this.hddcWyCraterRepository.findById(uuid).orElse(null);
         return hddcWyCrater;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyCraterEntity saveHddcWyCrater(HddcWyCraterEntity hddcWyCrater) {
        String uuid = UUIDGenerator.getUUID();
        hddcWyCrater.setUuid(uuid);
        if(StringUtils.isEmpty(hddcWyCrater.getCreateUser())){
            hddcWyCrater.setCreateUser(PlatformSessionUtils.getUserId());
        }
        hddcWyCrater.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcWyCrater.setIsValid("1");

        HddcCraterEntity hddcCraterEntity=new HddcCraterEntity();
        BeanUtils.copyProperties(hddcWyCrater,hddcCraterEntity);
        hddcCraterEntity.setExtends4(hddcWyCrater.getTown());
        hddcCraterEntity.setExtends5(String.valueOf(hddcWyCrater.getLon()));
        hddcCraterEntity.setExtends6(String.valueOf(hddcWyCrater.getLat()));
        this.hddcCraterRepository.save(hddcCraterEntity);

        this.hddcWyCraterRepository.save(hddcWyCrater);
        return hddcWyCrater;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyCraterEntity updateHddcWyCrater(HddcWyCraterEntity hddcWyCrater) {
        HddcWyCraterEntity entity = hddcWyCraterRepository.findById(hddcWyCrater.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcWyCrater);
        hddcWyCrater.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcWyCrater.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcWyCraterRepository.save(hddcWyCrater);
        return hddcWyCrater;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcWyCraters(List<String> ids) {
        List<HddcWyCraterEntity> hddcWyCraterList = this.hddcWyCraterRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcWyCraterList) && hddcWyCraterList.size() > 0) {
            for(HddcWyCraterEntity hddcWyCrater : hddcWyCraterList) {
                this.hddcWyCraterRepository.delete(hddcWyCrater);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    /**
     * 查询柱状图的值
     * @param queryParams
     * @return
     */
    @Override
    public BigInteger queryHddcWyCrater(HddcAppZztCountVo queryParams) {
        BigInteger bigInteger = hddcWyCraterNativeRepository.queryHddcWyCrater(queryParams);
        return bigInteger;
    }

    /**
     * 查询用户的表单列表
      * @param userId
     * @param taskId
     * @param projectId
     * @param isValid
     * @return
     */
    @Override
    public List<HddcWyCraterEntity> findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(String userId, String taskId, String projectId, String isValid) {
        List<HddcWyCraterEntity> list = hddcWyCraterRepository.findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(userId, taskId, projectId, isValid);
        return list;
    }

    /**
     * Excel导出
     * @param queryParams
     * @param response
     */
    @Override
    public void exportFile(HddcAppZztCountVo queryParams, HttpServletResponse response) {
        List<HddcWyCraterEntity> hddcWyCraterEntity = hddcWyCraterNativeRepository.exportCrater(queryParams);
        List<HddcWyCraterVO> list=new ArrayList<>();
        for (HddcWyCraterEntity entity:hddcWyCraterEntity) {
            HddcWyCraterVO hddcWyCraterVO=new HddcWyCraterVO();
            BeanUtils.copyProperties(entity,hddcWyCraterVO);
            list.add(hddcWyCraterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"火山口-点","火山口-点", HddcWyCraterVO.class,"火山口-点.xls",response);
    }

    /**
     * excel导入
     * @param file
     * @param response
     * @return
     */
    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcWyCraterVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcWyCraterVO.class, params);
            List<HddcWyCraterVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcWyCraterVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcWyCraterVO hddcWyCraterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + hddcWyCraterVO.getRowNum() + "行" + hddcWyCraterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcWyCraterVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcWyCraterEntity hddcWyCraterEntity = new HddcWyCraterEntity();
            HddcWyCraterVO hddcWyCraterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(hddcWyCraterVO, hddcWyCraterEntity);
            saveHddcWyCrater(hddcWyCraterEntity);
        }
    }

    @Override
    public List<HddcWyCraterEntity> findAllByCreateUserAndIsValid(String userId,String isValid) {
        List<HddcWyCraterEntity> list = hddcWyCraterRepository.findAllByCreateUserAndIsValid(userId, isValid);
        return list;
    }

    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcWyCraterEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyCraterRepository.queryHddcA1InvrgnhasmaterialtablesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcWyCraterEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyCraterRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskId
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcWyCraterEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyCraterRepository.queryHddcA1InvrgnhasmaterialtablesByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcWyCraterEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyCraterRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }

    }


}
